package webfilter.application.ipcount;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @description 利用filter统计访问showIpCnt.jsp页面的Ip的次数
 *              同时利用Listener的最原始的初始化能力, 来new出个map, 将其丢到域中;
 *
 * @author linshuo
 *
 */
public class CountIpFilter implements Filter {

    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletContext app = filterConfig.getServletContext();
        @SuppressWarnings("unchecked")
        Map<String, Integer> map = (Map<String, Integer>) app.getAttribute("mapIp2Cnt");
        String ip = request.getRemoteAddr();
        if (map.containsKey(ip)) {
            int newValue = map.get(ip);
            newValue++;
            map.put(ip, newValue);
        }
        else {
            map.put(ip, 1);
        }
        app.setAttribute("mapIp2Cnt", map);
        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }

}
